package com.wenjiang.filter;

import com.wenjiang.common.annotation.RequireToken;
import com.wenjiang.common.exception.TokenException;
import com.wenjiang.common.util.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截token 需要token的方法 （用户id）
 */
@Component
@Slf4j
public class TokenFilter extends HandlerInterceptorAdapter {

    /**
     * 拦截方法执行前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断有没有需要token的注解
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        if (handlerMethod.hasMethodAnnotation(RequireToken.class)) {
            //获取token
            String token = request.getHeader("token");

            //判断token是否为空
            if(token==null||token.equals("null")){
                log.info("token为空");
                throw  new TokenException();
            }

            // 判断token是否过期
           if(JWTUtil.isExpired(token)){
               throw  new TokenException();
           }

           //判断token是否合法
            if(!JWTUtil.verify(token)){
                throw  new TokenException();
            }

            return true;


        }
        else{
            //没有注解则进行放行
            return true;
        }

    }
}
